<template>
  <div class="common-container">
    <div class="common-content">
      <div class="payment-wrapper">
        <h2 class="page-title">订单支付</h2>
        
        <el-card class="payment-card">
          <!-- 支付金额 -->
          <div class="payment-amount">
            <div class="amount-label">订单金额</div>
            <div class="amount-value">¥{{ amount.toFixed(2) }}</div>
          </div>
          
          <!-- 支付方式选择 -->
          <div class="section">
            <h3 class="section-title">选择支付方式</h3>
            <div class="payment-methods">
              <div 
                v-for="method in paymentMethods" 
                :key="method.code"
                class="payment-method-item"
                :class="{ 'active': selectedMethod === method.code }"
                @click="selectMethod(method.code)"
              >
                <div class="method-icon">
                  <i :class="method.icon"></i>
                </div>
                <div class="method-name">{{ method.name }}</div>
                <el-radio 
                  v-model="selectedMethod" 
                  :label="method.code" 
                  :border="false" 
                  class="method-radio"
                ></el-radio>
              </div>
            </div>
          </div>
          
          <!-- 订单信息 -->
          <div class="section">
            <h3 class="section-title">订单信息</h3>
            <div class="order-info">
              <div class="info-item">
                <span class="label">订单编号:</span>
                <span class="value">{{ orderNo }}</span>
              </div>
              <div class="info-item">
                <span class="label">支付方式:</span>
                <span class="value">{{ getSelectedMethodName() }}</span>
              </div>
            </div>
          </div>
          
          <!-- 支付按钮 -->
          <div class="payment-actions">
            <el-button type="primary" size="large" @click="submitPayment" :disabled="loading || !canPay">
              <span v-if="loading"><i class="el-icon-loading"></i> 处理中...</span>
              <span v-else>确认支付</span>
            </el-button>
            <el-button size="large" @click="cancelPayment">取消</el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Payment",
  data() {
    return {
      orderId: '',
      amount: 0,
      orderNo: '',
      selectedMethod: 'alipay', // 默认支付宝
      paymentMethods: [
        { code: 'alipay', name: '支付宝', icon: 'el-icon-ali-pay' },
        { code: 'wechat', name: '微信支付', icon: 'el-icon-wechat' },
        { code: 'creditcard', name: '银行卡支付', icon: 'el-icon-credit-card' }
      ],
      loading: false,
      canPay: true
    };
  },
  created() {
    // 获取URL参数
    this.orderId = this.$route.query.orderId;
    this.amount = parseFloat(this.$route.query.amount) || 0;
    
    if (!this.orderId) {
      this.$message.warning('订单ID不存在');
      setTimeout(() => {
        this.$router.push('/front/orderList');
      }, 1500);
      return;
    }
    
    // 加载订单信息
    this.loadOrderInfo();
  },
  methods: {
    loadOrderInfo() {
      this.request.get(`/orders/${this.orderId}`).then(res => {
        if (res.code === 200 && res.data) {
          // 处理返回数据格式，确保与页面展示字段一致
          this.orderNo = res.data.no || res.data.orderNo; // 映射订单编号
          this.amount = res.data.totalPrice || res.data.total || this.amount; // 映射订单金额
          
          // 检查订单状态是否为待支付（支持数字和字符串状态值）
          const status = res.data.status;
          if (status !== 1 && status !== '待支付') {
            this.canPay = false;
            this.$message.warning('该订单状态不支持支付');
            setTimeout(() => {
              this.$router.push(`/front/orderDetail?orderId=${this.orderId}`);
            }, 1500);
          }
        } else {
          this.$message.error(res.msg || '获取订单信息失败');
        }
      }).catch(error => {
        console.error('获取订单信息失败:', error);
        this.$message.error('获取订单信息失败');
      });
    },
    
    selectMethod(methodCode) {
      this.selectedMethod = methodCode;
    },
    
    getSelectedMethodName() {
      const method = this.paymentMethods.find(m => m.code === this.selectedMethod);
      return method ? method.name : '';
    },
    
    submitPayment() {
      if (!this.canPay) {
        this.$message.warning('该订单状态不支持支付');
        return;
      }
      
      this.loading = true;
      
      const paymentData = {
        orderId: this.orderId,
        paymentMethod: this.selectedMethod,
        amount: this.amount
      };
      
      this.request.post("/payment/create", paymentData).then(res => {
        this.loading = false;
        
        if (res.code === 200) {
          // 模拟支付成功，实际项目中应该跳转到相应支付平台
          this.$message.success('支付成功');
          
          // 延迟跳转到订单详情页，模拟支付过程
          setTimeout(() => {
            this.$router.push(`/front/orderDetail?orderId=${this.orderId}`);
          }, 1500);
        } else {
          this.$message.error(res.msg || '支付失败');
        }
      }).catch(error => {
        this.loading = false;
        console.error('支付请求失败:', error);
        this.$message.error('支付失败，请稍后重试');
      });
    },
    
    cancelPayment() {
      this.$router.push(`/front/orderDetail?orderId=${this.orderId}`);
    }
  }
};
</script>

<style scoped>
.common-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.common-content {
  margin-bottom: 20px;
}

.payment-wrapper {
  width: 100%;
}

.page-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #303133;
  font-weight: 500;
}

.payment-card {
  background-color: #fff;
  max-width: 600px;
  margin: 0 auto;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.payment-amount {
  text-align: center;
  padding: 40px 0;
  background-color: #fafafa;
  margin-bottom: 30px;
  border-radius: 4px;
}

.amount-label {
  font-size: 18px;
  color: #606266;
  margin-bottom: 10px;
}

.amount-value {
  font-size: 48px;
  color: #f56c6c;
  font-weight: bold;
}

.section {
  margin-bottom: 30px;
  padding: 0 20px;
}

.section-title {
  font-size: 16px;
  margin-bottom: 15px;
  color: #303133;
  font-weight: 500;
}

.payment-methods {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.payment-method-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border: 2px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 150px;
  position: relative;
}

.payment-method-item:hover {
  border-color: #c0c4cc;
}

.payment-method-item.active {
  border-color: #409eff;
}

.method-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #409eff;
}

.method-name {
  color: #303133;
}

.method-radio {
  position: absolute;
  right: 15px;
}

.order-info {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  width: 100px;
  color: #909399;
}

.value {
  color: #303133;
}

.payment-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
  margin-bottom: 20px;
  padding: 0 20px;
}

.payment-actions .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .common-container {
    padding: 10px;
  }
  
  .payment-card {
    max-width: 100%;
  }
  
  .section {
    padding: 0 15px;
  }
  
  .payment-methods {
    flex-direction: column;
    gap: 10px;
  }
  
  .payment-method-item {
    min-width: 100%;
  }
  
  .payment-actions {
    flex-direction: column;
    padding: 0 15px;
  }
  
  .payment-actions .el-button {
    width: 100%;
  }
  
  .amount-value {
    font-size: 36px;
  }
}
</style>